﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Typing_GUI
{
    public partial class frmEditTextLesson : Form
    {

        #region "BIẾN"
       
        //Các ký tự đặc biệt
        char[] specialChar ={ '+', '-', '.', ',', '/', '?', '"', ':', '\\', ';', '=', '\'', '`', '~', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '|' };
        //Biến đếm số đoạn văn
        int paragraphCount = 0;
        //List danh sách đoạn văn
        List<string> ParagraphList = new List<string>();
        //ID đăng nhập người dùng
        public int editorID;
        //Mã bài tập
        public int LessonID;
       
        //string tenbai;
        //string thoigian;
        //string mota;
        public bool updated;
        public bool adminUse;
        public string username = "";
        public string levelLesson = "";
        public CLASS.CBaiTap lesson = new Typing_GUI.CLASS.CBaiTap();
        #endregion
        #region "Hàm kiểm tra nhập liệu"
        //Hàm kiểm tra Tên bài học
        bool CheckLessonName(string lsName)
        {

            lsName = lsName.Trim();
            if (lsName == "")
                return false;
            for (int i = 0; i < lsName.Length; i++)
                for (int j = 0; j < specialChar.Length; j++)
                    if (lsName[i].Equals(specialChar[j]))
                        return false;
            return true;

        }
        //Hàm kiểm tra chuỗi số
        bool isNumber(string num)
        {
            if (num.Length < 1)
                return false;
            for (int i = 0; i < num.Length; i++)
                if (!char.IsNumber(num[i]))
                    return false;
            return true;
        }
        //Hàm kiểm tra nội dung của đoạn văn bản
        bool CheckParagraph(string paragraph)
        {
            paragraph = paragraph.Trim();
            if (paragraph == "")
                return false;
            return true;
        }
        //Hàm lấy dữ liệu của 1 bài tập
        void LoadLessson(int lessonID)
        {
            DataTable dt = CLASS.CBaiTap.GetLesson(lessonID);
            if (dt.Rows.Count > 0)
            {
               
                DataRow row = dt.Rows[0];
                txtLessonName.Text = row["TenBaiTap"].ToString();
                txtDescription.Text = row["MoTa"].ToString();
                txtMaxScore.Text = row["DiemToiDa"].ToString();
                txtTime.Text = row["ThoiGian"].ToString();
                chbState.Checked = bool.Parse(row["TinhTrang"].ToString());
                LoadLevel();
                LoadUser();
                cobUser.SelectedValue = int.Parse(row["nguoisoan"].ToString());
                combLevel.SelectedValue = int.Parse(row["CapDoBaiTap"].ToString());
                string[] strParagraph = row["NoiDung"].ToString().Split(new string[] { "[P]" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < strParagraph.Length; i++)
                {
                    string str = "Paragraph " + (i + 1).ToString();
                    lbParagraphs.Items.Add(str);
                    ParagraphList.Add(strParagraph[i]);
                    paragraphCount++;
                }
                lblParagraphCount.Text = paragraphCount.ToString();
                if (strParagraph.Length > 0)
                {
                    txtParagraph.Text = strParagraph[0];
                    lbParagraphs.SelectedItem = lbParagraphs.Items[0];
                } 
            }
        }
        //Hàm load danh sách level
        void LoadLevel()
        {
            string sql = "select*from CapDoBaiTap";
            DataTable dt = CLASS.DataProvider.ExecuteQuery(sql);
            combLevel.DataSource = dt;
            combLevel.DisplayMember = "TenCapDo";
            combLevel.ValueMember = "MaCapDoBaiTap";
        }

        void LoadUser()
        {
            string sql = "select tendangnhap,manguoidung from nguoidung";
            DataTable dt = CLASS.DataProvider.ExecuteQuery(sql);
            cobUser.DataSource = dt;
            cobUser.DisplayMember = "tendangnhap";
            cobUser.ValueMember = "Manguoidung";
        }
        #endregion
        public frmEditTextLesson()
        {
            InitializeComponent();
        }

        private void btnAddParagraph_Click(object sender, EventArgs e)
        {
            if (CheckParagraph(txtParagraph.Text))
            {
                string str = "Paragraph ";
                paragraphCount++;
                lbParagraphs.Items.Add(str + paragraphCount.ToString());
                ParagraphList.Add(txtParagraph.Text);
                txtParagraph.Text = "";
                lblParagraphCount.Text = paragraphCount.ToString();
            }
            else
            {
                MessageBox.Show("Paragraph is not valid");
                txtParagraph.Focus();
                return;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {

            if (!CheckParagraph(txtParagraph.Text))
            {
                MessageBox.Show("Paragraph is not valid");
                txtParagraph.Focus();
                return;
            }
            else
            {
                int index = lbParagraphs.SelectedIndex;
                if (txtParagraph.Text.Length > 0)
                {
                    ParagraphList[index] = txtParagraph.Text;
                }
            }
        }

        private void btnClearParagraph_Click(object sender, EventArgs e)
        {
            txtParagraph.Text = "";
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int index = lbParagraphs.SelectedIndex;
            if (index != -1)
            {
                ParagraphList.RemoveAt(index);
                lbParagraphs.Items.RemoveAt(index);
                txtParagraph.Text = "";
            }
        }

        private void btnUpdateLesson_Click(object sender, EventArgs e)
        {
            if (!CheckLessonName(txtLessonName.Text))
            {
                MessageBox.Show("Lesson Name is not valid");
                txtLessonName.Focus();
                return;
            }
            if (!isNumber(txtTime.Text))
            {
                MessageBox.Show("Time must be an integer");
                txtTime.Focus();
                return;
            }
            if (ParagraphList.Count < 4)
            {
                MessageBox.Show("Paragraph count must great than 4");
                return;
            }
            //lesson = new Typing_GUI.CLASS.CBaiTap();
            lesson.Mabaitap = LessonID;
            lesson.Tenbaitap = CLASS.CBaiTap.RemoveQuote(txtLessonName.Text);
            lesson.Diemtoida = int.Parse(txtMaxScore.Text);
            lesson.Thoigian = int.Parse(txtTime.Text);
            lesson.Mota = CLASS.CBaiTap.RemoveQuote(txtDescription.Text);
            lesson.Loaibaitap = 1;
            if(adminUse==false)
                lesson.Nguoisoan = editorID;
            else
                lesson.Nguoisoan=int.Parse(cobUser.SelectedValue.ToString());
            lesson.TinhTrang = chbState.Checked;
            lesson.Capdobaitap = int.Parse(combLevel.SelectedValue.ToString());
            string strParagraphs = "";
            for (int i = 0; i < ParagraphList.Count; i++)
            {
                strParagraphs += ParagraphList[i];
                if (i < ParagraphList.Count - 1)
                {
                    strParagraphs += "[P]";
                }
            }
            lesson.Noidung = CLASS.CBaiTap.RemoveQuote(strParagraphs);
            if (lesson.UpdateLesson())
            {
                updated = true;
                username = cobUser.Text;
                levelLesson = combLevel.Text;
                MessageBox.Show("Lesson have updated successful!");
                this.Close();
            }   
            else
                MessageBox.Show("Lesson have updated failed!"); 
            
        }

        private void btnClearField_Click(object sender, EventArgs e)
        {
            txtLessonName.Text = "";
            txtMaxScore.Text = "0";
            txtDescription.Text = "";
            txtParagraph.Text = "";
            txtTime.Text = "";
            combLevel.SelectedIndex = 0;
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lbParagraphs_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = lbParagraphs.SelectedIndex;
            if (index != -1)
            {
                txtParagraph.Text = ParagraphList[index];
                btnDelete.Enabled = true;
                btnUpdate.Enabled = true;
            }
        }


        private void frmEditTextLesson_Load(object sender, EventArgs e)
        {
            //LessonID = 10;
            LoadLessson(LessonID);
            string un = CLASS.CNguoiDung.SetAvatar_Level(editorID, pbAvatar, pbLevel);
            lblUsername.Text = un;
        }

    }
}